package com.yndsoft.jc.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.*;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.widget.Button;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yndsoft.jc.MyApplication;
//import com.yndsoft.jc.gallerfinal.FrescoImageLoader;
import com.yndsoft.jc.model.Contact;
import com.yndsoft.jc.model.KeyValue_String;
import com.yndsoft.jc.model.Member;
import com.yndsoft.jc.model.ReturnMsg;
import com.yndsoft.jc.model.XYUpdate;
import com.yndsoft.jc.model.XYVersion;
import com.yndsoft.jc.R;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import cn.finalteam.galleryfinal.CoreConfig;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.ImageLoader;
import cn.finalteam.galleryfinal.ThemeConfig;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2016-08-05.
 */
public class CommMethodUtils {
    public static String[] phototype = new String[]{"拍照", "图库"};
    public static String[] sex = new String[]{"保密", "男", "女"};
    public static String[] business = new String[]{"其他", "制片", "发行", "宣传", "院线", "影管", "影院", "周边服务", "行业监管"};

    // 获得照片路径
    public static String getPhotoPath() {
        return Environment.getExternalStorageDirectory() + "/film/";
    }

    // 取当前时间为照片名
    public static String getPhotoName() {
        return DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
    }

    public static boolean isLogin(Activity activity) {
        boolean sp_login = false;
        SharedPreferences sp = activity.getSharedPreferences(activity.getString(R.string.sp_member), Context.MODE_PRIVATE);
        return sp_login;
    }

    public static Member getMember(Activity activity) {
        Member member = null;
        SharedPreferences sp = activity.getSharedPreferences(activity.getString(R.string.sp_member), Context.MODE_PRIVATE);
        if (sp != null) {
            String sp_film = sp.getString(activity.getString(R.string.sp_jc), "");
            if (sp_film != "" && sp_film != null) {
                Type f_type = new TypeToken<Member>() {
                }.getType();
                member = (Member) (new Gson().fromJson(sp_film, f_type));
            }
        }
        return member;
    }

    public static Integer getMemberID(Activity activity) {
        Integer mid = 0;
        Member member = getMember(activity);
        if (member != null) {
            mid = member.getId();
        }
        return mid;
    }

    public static String getUrlParams(HashMap<String, String> map) {
        String params = "";
        if (params != null) {
            Set set = map.keySet();
            for (Iterator iter = set.iterator(); iter.hasNext(); ) {
                String key = (String) iter.next();
                String value = (String) map.get(key);
                params += "&" + key + "=" + value;
            }
            params = "?" + params.substring(1, params.length());
        }
        return params;
    }

    //HashMap 升序排序
    public void MapSort(HashMap map) {
        //这里将map.entrySet()转换成list
        List<Map.Entry<Integer, Object>> list_t = new ArrayList<Map.Entry<Integer, Object>>(map.entrySet());
        //升序排序
        Collections.sort(list_t, new Comparator<Map.Entry<Integer, Object>>() {
            public int compare(Map.Entry<Integer, Object> o1, Map.Entry<Integer, Object> o2) {
                return (o1.getKey()).compareTo(o2.getKey());
            }
        });
        HashMap<Integer, Object> map_t = new HashMap<Integer, Object>();
        for (Map.Entry<Integer, Object> mapping : list_t) {
            map_t.put(mapping.getKey(), mapping.getValue());
        }
    }

    public static void getModel(final Activity activity, String info, Object object) {
        Type type = new TypeToken<ReturnMsg>() {
        }.getType();
        Object fromJson = new Gson().fromJson(info, type);
        final ReturnMsg returnMsg = (ReturnMsg) fromJson;
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                switch (returnMsg.getCode()) {
                    case 0:
                        Toast.makeText(activity.getApplicationContext(), "获取详情失败！", Toast.LENGTH_SHORT).show();
                        break;
                    case 1:
                        break;
                    default:
                        break;
                }
            }
        });
    }

    //弹出框
    public static void showInfoDialog(Context context, String message) {
        showInfoDialog(context, message, "提示", "确定", null);
    }

    //弹出框
    public static void showReturnDialog(Context context) {
        showReturnDialog(context, "提示", "确定", null);
    }

    //正则：email
    public static boolean isValidEmail(String paramString) {
        String regex = "[a-zA-Z0-9_\\.]{1,}@(([a-zA-z0-9]-*){1,}\\.){1,3}[a-zA-z\\-]{1,}";
        if (paramString.matches(regex)) {
            return true;
        } else {
            return false;
        }
    }

    //正则：手机
    public static boolean isValidPhone(String paramString) {
        String regex = "^1\\d{10}$";
        if (paramString.matches(regex)) {
            return true;
        }
        return false;
    }

    // 弹出 对话框
    public static void showInfoDialog(Context context, String message, String titleStr, String positiveStr, DialogInterface.OnClickListener onClickListener) {
        AlertDialog.Builder localBuilder = new AlertDialog.Builder(context);
        localBuilder.setTitle(titleStr);
        localBuilder.setMessage(message);
        if (onClickListener == null)
            onClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            };
        localBuilder.setPositiveButton(positiveStr, onClickListener);
        localBuilder.show();
    }

    // 弹出 退出提示框
    public static void showReturnDialog(Context context, String titleStr, String positiveStr, DialogInterface.OnClickListener onClickListener) {
        Dialog alertDialog = new AlertDialog.Builder(context)
                .setTitle(titleStr).setMessage("您确定要退出吗?")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        MyApplication.getInstance().exit();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                    }
                }).create();
        alertDialog.show();
    }

    // 弹出 进度
    public static void showProgressDialog(Context context, ProgressDialog progressDialog) {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(context);
        }
        progressDialog.setTitle("");
        progressDialog.setMessage("");
        progressDialog.show();
    }

    //关闭 进度
    public static void closeProgressDialog(ProgressDialog progressDialog) {
        if (progressDialog != null)
            progressDialog.dismiss();
    }

    //初始化GallerFinal
    public static void initGalleryFinal(Activity activity) {
        //1、配置主题
        ThemeConfig theme = new ThemeConfig.Builder()
                .setTitleBarBgColor(R.color.black)
                .build();
        //2、配置功能
        FunctionConfig functionConfig = new FunctionConfig.Builder()
                .setEnableCamera(true)
                .setEnableEdit(true)
                .setEnableCrop(true)
                .setEnableRotate(true)
                .setCropSquare(true)
                .setEnablePreview(true)
                .build();
        //3、配置imageloader
//        ImageLoader imageloader = new FrescoImageLoader(activity);
        //4、设置核心配置信息
//        CoreConfig coreConfig = new CoreConfig.Builder(activity, imageloader, theme)
//                .setFunctionConfig(functionConfig)
//                .build();
//        GalleryFinal.init(coreConfig);
    }

    public static FunctionConfig getFunctionConfig(Activity activity) {
        initGalleryFinal(activity);
        final FunctionConfig functionConfig = new FunctionConfig
                .Builder()
                .setMutiSelectMaxSize(1)
                .setEnableEdit(true) //开启编辑功能
                .setEnableRotate(false) //开启旋转功能
                .setEnableCamera(false) //开启相机功能
                .setEnableCrop(true) //开启裁剪功能
                .setCropWidth(500)//裁剪宽度
                .setCropHeight(500)//裁剪高度
                .setCropSquare(true)//裁剪正方形
                .setRotateReplaceSource(false)//配置选择图片时是否替换原始图片，默认不替换
                .setCropReplaceSource(false)//配置裁剪图片时是否替换原始图片，默认不替换
                .setForceCrop(true)//启动强制裁剪功能,一进入编辑页面就开启图片裁剪，不需要用户手动点击裁剪，此功能只针对单选操作
                .setForceCropEdit(false)//在开启强制裁剪功能时是否可以对图片进行编辑（也就是是否显示旋转图标和拍照图标）
                .setEnablePreview(false)//是否开启预览功能
                .build();
        return functionConfig;
    }

    /*
    * 判断sdcard是否被挂载
    */
    public static boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 调用相机
     */
    public static Intent openCamera(Uri uri) {
        //实例化一个intent，并指定action
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        //指定一个图片路径对应的file对象
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        //return-data:是将结果保存在data中返回，在onActivityResult中，直接调用intent.getdata()就可以获取值了，这里设为fase，就是不让它保存在data中
        intent.putExtra("return-data", false);
        return intent;
    }

    /**
     * 打开相册
     */
    public static Intent openGallery() {
        Intent intent;
        /* 开启Pictures画面Type设定为image */
        if (Build.VERSION.SDK_INT < 19) {
            /* 使用Intent.ACTION_GET_CONTENT这个Action */
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        //activity.setResult(resultCode, intent);
        //传递参数
        //intent.putExtra("result", resultCode);
        return intent;
    }

    /*
     * 剪切图片
     */
    public static Intent crop(Uri uri, Integer aspectX, Integer aspectY, Integer outputX, Integer outputY) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，4：3
        intent.putExtra("aspectX", aspectX);
        intent.putExtra("aspectY", aspectY);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("outputFormat", "JPEG");// 返回图片格式
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        //activity.setResult(resultCode, intent);
        //传递参数
        //intent.putExtra("result", resultCode);
        return intent;
    }

    /**
     * 保存文件
     */
    public static File saveFile(Context context, Bitmap bm, String fileName) {
        try {
            //getCacheDir()方法用于获取/data/data//cache目录, 对于 应用详情里的 “清除数据” 选项
            //getFilesDir()方法用于获取/data/data//files目录, 对于 应用详情里的 “清除缓存” 选项
            //PHOTO_FILE_URI = this.getCacheDir() + fileName;
            //PHOTO_FILE_URI = this.getFilesDir() + fileName;
            //PHOTO_FILE_URI = Environment.getExternalStorageDirectory() + "/" + fileName + ".jpg";
            //Toast.makeText(ImageTestActivity.this, "剪切路径：" + PHOTO_FILE_URI, Toast.LENGTH_LONG).show();
            //String filePath = "/sdcard/yndsoft/";
            //根目录，逍遥 之下
            //String filePath = Environment.getExternalStorageDirectory() + "/逍遥/";
            String filePath = Environment.getExternalStorageDirectory() + "/film/";
            //String filePath = getDiskCacheDir(context);
            //Toast.makeText(context, "文件路径：" + filePath, Toast.LENGTH_SHORT).show();
            File file_t = new File(filePath);
            if (!file_t.exists()) {
                file_t.mkdir();
            }
            File file = new File(filePath + fileName + ".jpg");
            //将bitmap压缩后写入输出流(参数依次为图片格式、图片质量和输出流)
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
            //Toast.makeText(context, "图片保存路径：" + file.getPath(), Toast.LENGTH_SHORT).show();
            return file;
        } catch (Exception ex) {
            Toast.makeText(context, "图片保存失败！", Toast.LENGTH_SHORT).show();
            return null;
        }
    }

    //从Uri中获取Bitmap格式的图片
    public static Bitmap decodeUriAsBitmap(Context context, Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 将Bitmap写入SD卡中的一个文件中,并返回写入文件的Uri
     *
     * @param bm
     * @return
     */
    public static Uri saveBitmap(Bitmap bm) {
        //新建文件夹用于存放裁剪后的图片
        File tmpDir = new File(Environment.getExternalStorageDirectory() + "/film/");
        if (!tmpDir.exists()) {
            tmpDir.mkdir();
        }
        //新建文件存储裁剪后的图片
        File img = new File(tmpDir.getAbsolutePath() + "/temp.jpg");
        try {
            //打开文件输出流
            FileOutputStream fos = new FileOutputStream(img);
            //将bitmap压缩后写入输出流(参数依次为图片格式、图片质量和输出流)
            bm.compress(Bitmap.CompressFormat.PNG, 85, fos);
            //刷新输出流
            fos.flush();
            //关闭输出流
            fos.close();
            //返回File类型的Uri
            return Uri.fromFile(img);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将content类型的Uri转化为文件类型的Uri
     *
     * @param uri
     * @return
     */
    public static Uri convertUri(Context context, Uri uri) {
        InputStream is;
        try {
            //Uri ----> InputStream
            is = context.getContentResolver().openInputStream(uri);
            //InputStream ----> Bitmap
            Bitmap bm = BitmapFactory.decodeStream(is);
            //关闭流
            is.close();
            return saveBitmap(bm);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    //保存路径
    public static String getDiskCacheDir(Context context) {
        String cachePath = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return cachePath;
    }

    //上传图片
    public static void postAsynFile(final Activity activity, final String img_temp, File upload_file) {
        String url_upload = activity.getString(R.string.url_upload);
        OkHttpClient okHttpClient = new OkHttpClient();
        MediaType MEDIA_TYPE_JPG = MediaType.parse("image/jpg");

//        RequestBody requestBody = new MultipartBody.Builder()
//                .setType(MultipartBody.FORM)
//                .addFormDataPart("aaaa", "sss")
//                .addFormDataPart("bbbb", "ccc")
//                .addFormDataPart("image", upload_file.getName(), RequestBody.create(MEDIA_TYPE_JPG, upload_file))
//                .build();

        Request request = new Request.Builder().url(url_upload).post(RequestBody.create(MEDIA_TYPE_JPG, upload_file)).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException ex) {
                //Toast.makeText(context, "上传失败..." + msg, Toast.LENGTH_LONG).show();
                final String msg = ex.getMessage();
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, "上传失败..." + msg, Toast.LENGTH_LONG).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //Toast.makeText(getApplicationContext(), response.body().string(), Toast.LENGTH_LONG).show();
                final String msg = response.body().string();
                //img_temp = msg;
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //img_temp = msg;
                        Toast.makeText(activity, "上传成功...;Img:" + msg, Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
    }

    //设置按钮可点，颜色原色
    public static void setButtonEnableTrue(boolean flag, Button btn) {
        flag = false;
        //btn.setBackgroundResource(R.drawable.login_bg);
        btn.setEnabled(true);
    }

    //设置按钮不可点，颜色灰色
    public static void setButtonEnableFalse(boolean flag, Button btn) {
        flag = true;
        btn.setBackgroundResource(R.color.button_pressed);
        btn.setEnabled(false);
    }

    /**
     * 得到手机通讯录联系人信息
     **/
    public static void getPhoneContacts(Context context, List<Contact> list) {
        ContentResolver resolver = context.getContentResolver();
        // 获取手机联系人
        Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME},
                null, null, null);
        if (phoneCursor != null) {
            while (phoneCursor.moveToNext()) {
                Contact contact = new Contact();
                //得到手机号码
                String phone = phoneCursor.getString(0);
                //当手机号码为空的或者为空字段 跳过当前循环
                if (CommMethodUtils.isValidPhone(phone)) {
                    //得到联系人名称
                    String name = phoneCursor.getString(1);
                    contact.setPhone(phone);
                    contact.setName(name);
                    list.add(contact);
                }
            }
            phoneCursor.close();
        }
    }

    /**
     * 得到手机通讯录联系人信息
     **/
    public static void getContacts(Context context, List<KeyValue_String> list) {
        ContentResolver resolver = context.getContentResolver();
        // 获取手机联系人
        Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        while (cursor.moveToNext()) {
            KeyValue_String keyvalue_string = new KeyValue_String();
            //得到手机号码
            String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            //当手机号码为空的或者为空字段 跳过当前循环
            if (CommMethodUtils.isValidPhone(phone)) {
                //得到联系人名称
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                keyvalue_string.setKey(phone);
                keyvalue_string.setValue(name);
                list.add(keyvalue_string);
            }
        }
        cursor.close();
    }

    /**
     * 分页查询系统联系人信息
     *
     * @param pageSize      每页最大的数目
     * @param currentOffset 当前的偏移量
     * @return
     */
    public static void getContactsByPage(Context context, int pageSize, int currentOffset, List<KeyValue_String> list) {
        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, "sort_key COLLATE LOCALIZED asc limit " + pageSize + " offset " + currentOffset);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                KeyValue_String keyvalue_string = new KeyValue_String();
                String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                keyvalue_string.setKey(phone);
                keyvalue_string.setValue(name);
                list.add(keyvalue_string);
            }
            cursor.close();
        }
    }

    /**
     * 获得系统联系人的所有记录数目
     *
     * @return
     */
    public static int getAllCounts(Context context) {
        int num = 0;
        // 使用ContentResolver查找联系人数据
        Cursor cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        // 遍历查询结果，获取系统中所有联系人
        while (cursor.moveToNext()) {
            num++;
        }
        cursor.close();
        return num;
    }

    //获取联系人数据的方法
    public static void getTongXunLu(final Context context, final List<HashMap<String, String>> list) {
        //因为读取系统联系人,可能是一个耗时操作,放置到子线程中处理
        new Thread() {
            public void run() {
                //1,获取内容解析器对象
                ContentResolver contentResolver = context.getContentResolver();
                //2,做查询系统联系人数据库表过程(读取联系人权限)
                Cursor cursor = contentResolver.query(
                        Uri.parse("content://com.android.contacts/raw_contacts"),
                        new String[]{"contact_id"},
                        null, null, null);
                list.clear();
                //3,循环游标,直到没有数据为止
                while (cursor.moveToNext()) {
                    String id = cursor.getString(0);
                    //4,根据用户唯一性id值,查询data表和mimetype表生成的视图,获取data以及mimetype字段
                    Cursor indexCursor = contentResolver.query(
                            Uri.parse("content://com.android.contacts/data"),
                            new String[]{"data1", "mimetype"},
                            "raw_contact_id = ?", new String[]{id}, null);
                    //5,循环获取每一个联系人的电话号码以及姓名,数据类型
                    HashMap<String, String> hashMap = new HashMap<String, String>();
                    while (indexCursor.moveToNext()) {
                        String data = indexCursor.getString(0);
                        String type = indexCursor.getString(1);
                        //6,区分类型去给hashMap填充数据
                        if (type.equals("vnd.android.cursor.item/phone_v2")) {
                            //数据非空判断
                            hashMap.put("phone", data);
                        } else if (type.equals("vnd.android.cursor.item/name")) {
                            hashMap.put("name", data);
                        }
                    }
                    indexCursor.close();
                    list.add(hashMap);
                }
                cursor.close();
                //7,消息机制,发送一个空的消息,告知主线程可以去使用子线程已经填充好的数据集合
                //mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    public static XYVersion getVersion(Context context) {
        XYVersion version = new XYVersion();
        try {
            //getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageManager packageManager = context.getPackageManager();
            PackageInfo pi = packageManager.getPackageInfo(context.getPackageName(), 0);
            // 获取版本号(内部识别号)
            version.setVersion(pi.versionName);
            version.setVersioncode(pi.versionCode);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return version;
    }

    //获取新版本
    public static void getUpdate(String url_version, final Activity activity, final Dialog dialog, int updateCode) {
        final int VersionCode = getVersion(activity).getVersioncode();
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url_version)
                    .get()
                    .build();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException ex) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(activity, "检查新版本出错!", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final InputStream stream = response.body().byteStream();
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            XYUpdate update = CommMethodUtils.parseUpdateXml(stream);
                            //updateCode = update.getVersion();
                        }
                    });
                }
            });
        } catch (Exception ex) {
            Toast.makeText(activity, "检查新版本出错：" + ex.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    //下载新版本
    public static void downUpdate(String url, final Activity activity, final Dialog dialog) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException arg1) {
                Toast.makeText(activity, "下载失败", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String DM_TARGET_FOLDER = File.separator + "a_download" + File.separator; //下载目标文件夹
                String destFileDir;     //目标文件存储的文件夹路径
                String destFileName;    //目标文件存储的文件名
                destFileDir = Environment.getExternalStorageDirectory() + DM_TARGET_FOLDER;
                destFileName = "好马驰.apk";
                File dir = new File(destFileDir);
                if (!dir.exists()) dir.mkdirs();
                final File file = new File(dir, destFileName);
                if (file.exists()) file.delete();

                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();

                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                    }
                    fos.flush();

                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dialog.dismiss();
                            Toast.makeText(activity, "下载成功", Toast.LENGTH_SHORT).show();
                            CommMethodUtils.installApk(activity, file);
                        }
                    });
                } catch (final Exception ex) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(activity, "下载失败:" + ex.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

    public static XYUpdate parseUpdateXml(InputStream stream) {
        XYUpdate update = new XYUpdate();
        try {
            // 实例化一个文档构建器工厂
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // 通过文档构建器工厂获取一个文档构建器
            DocumentBuilder builder = factory.newDocumentBuilder();
            // 通过文档通过文档构建器构建一个文档实例
            Document document = builder.parse(stream);
            // 获取XML文件根节点
            Element root = document.getDocumentElement();
            // 获得所有子节点
            NodeList childNodes = root.getChildNodes();
            for (int j = 0; j < childNodes.getLength(); j++) {
                // 遍历子节点
                Node childNode = (Node) childNodes.item(j);
                if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element childElement = (Element) childNode;
                    // 版本号
                    if ("version".equals(childElement.getNodeName())) {
                        update.setVersion(Integer.valueOf(childElement.getFirstChild().getNodeValue()));
                    }
                    // 名称
                    else if ("name".equals(childElement.getNodeName())) {
                        update.setName(childElement.getFirstChild().getNodeValue());
                    }
                    // 是否强制
                    else if ("force".equals(childElement.getNodeName())) {
                        update.setForce(Integer.valueOf(childElement.getFirstChild().getNodeValue()));
                    }
                    // 下载地址
                    else if (("url".equals(childElement.getNodeName()))) {
                        update.setUrl(childElement.getFirstChild().getNodeValue());
                    }
                    // 描述
                    else if (("description".equals(childElement.getNodeName()))) {
                        update.setDescription(childElement.getFirstChild().getNodeValue());
                    }
                }
            }
        } catch (Exception ex) {
            update = null;
        }
        return update;
    }

    //安装apk
    public static void installApk(Activity activity, File file) {
        Intent intent = new Intent();
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        //执行的数据类型
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        activity.startActivity(intent);
    }

    //保存文件
    public static File saveFile(Response response, String name) {
        File file;
        InputStream is = null;
        byte[] buf = new byte[2048];
        int len = 0;
        FileOutputStream fos = null;
        try {
            is = response.body().byteStream();
            final long total = response.body().contentLength();
            long sum = 0;
            String filePath = Environment.getExternalStorageDirectory() + "/";
            File file_t = new File(filePath);
            if (!file_t.exists()) {
                file_t.mkdir();
            }
            file = new File(filePath + name + ".apk");
            fos = new FileOutputStream(file);
            while ((len = is.read(buf)) != -1) {
                sum += len;
                fos.write(buf, 0, len);
                final long finalSum = sum;
                String load = String.valueOf(finalSum * 1.0f / total);
            }
            fos.flush();
            if (is != null) {
                is.close();
            }
            if (fos != null) {
                fos.close();
            }
            return file;
        } catch (Exception ex) {
            file = null;
        }
        return file;
    }

    //未测试 --- 2016.11.11
    public static File getFileFromServer(String path, ProgressDialog pd) throws Exception {
        //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            //获取到文件的大小
            pd.setMax(conn.getContentLength());
            InputStream is = conn.getInputStream();
            File file = new File(Environment.getExternalStorageDirectory(), "updata.apk");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                //获取当前下载量
                pd.setProgress(total);
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            return null;
        }
    }

//    //Fresco 清除磁盘缓存
//    public void clearDiskCache() {
//        Fresco.getImagePipeline().clearDiskCaches();
//    }
//
//    //Fresco 清除单张图片缓存
//    public void clearCacheBuUrl(String url) {
//        ImagePipeline imagePipeline = Fresco.getImagePipeline();
//        Uri uri = Uri.parse(url);
//        imagePipeline.evictFromDiskCache(uri);
//        //imagePipeline.evictFromCache(uri);  //这个包含了从内存和磁盘移除
//    }
}
